<template>
  <div class="final-found-item" v-if="(dataArr && dataArr.length > 0)">
    <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <found-item-view :dataArr="dataArr" :topTagLists="topTagLists" :advertisingData="advertisingData"
          :switchSelected="switchSelected" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<!-- 最终完美的组件 -->
<script setup lang="ts">
import { onMounted, ref } from "vue"
import { Api } from "@/utils/apis"
import FoundItemView from "@/components/HomeComponents/FoundComponents/FoundItemView.vue";
import { showToast } from "vant";
// import loading from "vant/lib/loading";
import type { DataType, AdvertisingDataType, topTagListsDataType } from "@/typings"

let loading = ref(false);
let finished = ref(false);
let refreshing = ref(false);
let dataArr = ref<DataType[]>([])
let topTagLists = ref<topTagListsDataType[]>([])
let advertisingData = ref<AdvertisingDataType[]>([])
let domainId = ref<number>()

const props = defineProps({
  domainId: {
    type: Number
  }
})
domainId.value = props.domainId

// 获取数据
const getgGneralData = async () => {
  let data = await Api.getgGneralData({
    domainId: domainId.value
  })
  dataArr.value = data?.data?.list
  topTagLists.value = data?.data?.topTagLists
}

// 获取push数据
const getPushData = async () => {
  let data = await Api.getgGneralData({
    domainId: domainId.value
  })
  dataArr.value.push(...data?.data?.list)
}

// 获取广告数据
const getAdvertising = async () => {
  let data = await Api.getAdvertising({
    category: "EXPLOREBANNER",
    extJson: `{"domainId":${domainId.value}}`
  })
  advertisingData.value = data[0].ads;
  // console.log(data);
}

const onLoad = () => {
  if (refreshing.value) {
    dataArr.value = [];
    refreshing.value = false;
  }
  // 异步更新数据
  //  axios 请求
  getPushData()

  // 加载状态结束 
  loading.value = false;

  // 数据全部加载完成
  if (dataArr.value.length >= 100) {
    finished.value = true;
  }
};

const onRefresh = () => {
  // 清空列表数据
  finished.value = false;

  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  onLoad();
  showToast('刷新成功');
};

// const switchSelected = (id, src) => {
const switchSelected = (id: number) => {
  // this.$nextTick(() => {
  dataArr.value.forEach(r => {
    if (r.itemId === id) {
      if (r.postData.postCount.viewCount == 1) {
        r.postData.postCount.viewCount = 0;
        r.postData.postCount.favoriteCount -= 1;
      } else {
        r.postData.postCount.viewCount = 1;
        r.postData.postCount.favoriteCount += 1;
      }
    }
  });
  // this.$store.commit("toggleMyLike", { id, src });
  // console.log(this.$store.state.myLike);
  // })
};


onMounted(() => {
  getgGneralData()
  getAdvertising()
})

</script>

<style lang="scss" scoped>

</style>